package com.pt5.pthouduan.entity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Component // 直接作为Spring组件
public class DatabaseStatsRecorder implements StatsRecorder  {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseStatsRecorder.class); // 修正logger

    @Autowired
    private DataSource dataSource;

    /**
     * 记录用户流量统计
     */
    @Override
    public void recordStats(
            String passkey,
            String infoHash,
            String ip,
            int port,
            String peerId,
            long uploaded,
            long downloaded) {

        String sql = """
            INSERT INTO peer_stats (
                passkey, info_hash, ip, port, peer_id,
                uploaded, downloaded, delta_upload, delta_download,
                share_ratio, last_updated
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ON DUPLICATE KEY UPDATE
                uploaded = uploaded + VALUES(delta_upload),
                downloaded = downloaded + VALUES(delta_download),
                share_ratio = CASE 
                    WHEN downloaded + VALUES(delta_download) = 0 THEN 0 
                    ELSE (uploaded + VALUES(delta_upload)) / (downloaded + VALUES(delta_download)) 
                END,
                last_updated = NOW()
            """;

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 计算增量
            long deltaUpload = calculateDelta(passkey, infoHash, ip, port, "uploaded", uploaded);
            long deltaDownload = calculateDelta(passkey, infoHash, ip, port, "downloaded", downloaded);
            double shareRatio = (downloaded == 0) ? 0 : (double) uploaded / downloaded;

            // 绑定参数
            bindParameters(stmt, passkey, infoHash, ip, port, peerId,
                    uploaded, downloaded, deltaUpload, deltaDownload, shareRatio);

            stmt.executeUpdate();

        } catch (SQLException e) {
            logger.error("流量统计失败: passkey={}, infoHash={}", passkey, infoHash, e);
            throw new RuntimeException("数据库写入失败", e);
        }
    }

    // 参数绑定封装
    private void bindParameters(PreparedStatement stmt,
                                String passkey, String infoHash, String ip, int port,
                                String peerId, long uploaded, long downloaded,
                                long deltaUpload, long deltaDownload, double shareRatio)
            throws SQLException {
        stmt.setString(1, passkey);
        stmt.setString(2, infoHash);
        stmt.setString(3, ip);
        stmt.setInt(4, port);
        stmt.setString(5, peerId);
        stmt.setLong(6, uploaded);
        stmt.setLong(7, downloaded);
        stmt.setLong(8, deltaUpload);
        stmt.setLong(9, deltaDownload);
        stmt.setDouble(10, shareRatio);
    }

    // 计算增量（私有方法）
    private long calculateDelta(String passkey, String infoHash, String ip, int port,
                                String column, long currentValue) {
        String querySql = "SELECT " + column + " FROM peer_stats " +
                "WHERE passkey=? AND info_hash=? AND ip=? AND port=?";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(querySql)) {

            stmt.setString(1, passkey);
            stmt.setString(2, infoHash);
            stmt.setString(3, ip);
            stmt.setInt(4, port);

            ResultSet rs = stmt.executeQuery();
            return rs.next() ? Math.max(0, currentValue - rs.getLong(1)) : currentValue;

        } catch (SQLException e) {
            logger.warn("增量计算失败，使用全量值", e);
            return currentValue;
        }
    }
}
